import { defineStore } from "pinia";
import { RouteRecordRaw } from "vue-router";
import router from "/@/router";
import authCache from "/@/utils/cache/authCache";
import { firstCharToUpper } from "/@/utils/common";
import { getRoutes } from "/@/api/main/system";
import { RouteItem } from "/@/api/main/system/models";
import { loopItem } from "/@/utils/treeData";

//部分复杂页面路由与页面组件路径映射关系
const pageUrlPath = {
  DataPermissionDef: "DataPermissionDef/DataPermissionDef",
  SupplierArchives: "SupplierArchives/SupplierArchives",
  CheckBill: "CheckBill/CheckBill",
};
function getPageComponentPath(pageUrl: string) {
  pageUrl = pageUrl.replace(/^\//, "");
  pageUrl = firstCharToUpper(pageUrl);
  return pageUrlPath[pageUrl] || pageUrl;
}

const dynamicModules = import.meta.glob("../views/**/*.vue");

function handlePath(path: string) {
  return path.replace(/^\//, "");
}

function handleMenuItem(
  routeData: RouteRecordRaw[],
  rootRouteName: string,
  firstFeaturePath: string | null,
  item: RouteItem,
  parentItems: RouteItem[]
) {
  if (item.children && item.children.length > 0) {
    parentItems.push(item);
    item.children.forEach((el) => {
      handleMenuItem(routeData, rootRouteName, firstFeaturePath, el, parentItems);
    });
    parentItems.pop();
  } else {
    item.children = void 0;
    let parentActions: string[] = [rootRouteName].concat(parentItems.map((el) => el.path));
    const route: RouteRecordRaw = {
      path: `/${parentActions.join("/")}/${item.path}`,
      name: item.path,
      component:
        dynamicModules[
          `../views/${rootRouteName}/${firstFeaturePath ? firstFeaturePath + "/" : ""}${getPageComponentPath(
            item.path
          )}.vue`
        ],
    };
    item.path = route.path;
    //动态加入路由数据
    router.addRoute(rootRouteName, route);
    routeData.push(route);
  }
}

export function handleMenuSort(menuData?: RouteItem[]) {
  if (menuData && menuData.length > 0) {
    menuData.sort((a, b) => {
      return a.sort - b.sort;
    });
    menuData.forEach((menuItem) => {
      handleMenuSort(menuItem.children);
    });
  }
}

export const useMenuStore = defineStore("menu", {
  state: (): { menuData: RouteItem[] } => {
    return {
      menuData: [],
    };
  },
  actions: {
    /**
     * 初始化菜单和路由
     * 将菜单转化为路由数据 并加入到vueRouter中
     */
    async initAuthMenu({ rootRouteName }: { rootRouteName: string }) {
      const userInfo = authCache.getUserInfo();
      if (!userInfo) return null;
      const menuData = await getRoutes();
      // const menuData = await getStaticMenuData();
      if (!menuData) return null;
      const roles = userInfo.roles || [];
      loopItem(
        menuData,
        (item, i, items) => {
          let isAuth = false;
          if (item.meta) {
            const menuRoles = item.meta.roles || [];
            for (let i = 0; i < roles.length; i++) {
              if (menuRoles.includes(roles[i])) {
                isAuth = true;
                break;
              }
            }
            if (!isAuth) {
              items.splice(i, 1);
            }
          }
          if (isAuth) {
            item.path = handlePath(item.path);
          }
        },
        {
          isReverse: true,
        }
      );
      handleMenuSort(menuData);
      const routeData: RouteRecordRaw[] = [];
      this.menuData = menuData;
      menuData.forEach((item) => {
        handleMenuItem(routeData, rootRouteName, item.path || null, item, []);
      });
      // console.log("===========>", menuData);
      return routeData;
    },
  },
});
